package com.dianning.fio.imp;

import java.io.*;

import org.apache.commons.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dianning.comm.Constant;
import com.dianning.comm.DianningUtil;
import com.dianning.comm.ImgUtil;
import com.dianning.fio.AvatarUploadFile;
import com.dianning.fio.UploadFile;

public class AvatarUploadFileImp implements AvatarUploadFile {
	private static final Log logger = LogFactory.getLog(AvatarUploadFileImp.class);	

  public AvatarUploadFileImp() {
  }

  /**
  *
  * @param toFileName String
  * @param uploadFile UploadFile
  * @param sysConfig SysConfig
  * @throws IOException
  */
 public boolean saveUploadFile(UploadFile uploadFile,long uid) throws
     IOException {
	 	boolean flag = true;
	 	DianningUtil.mkDirById(uid,Constant.AVATAR_PATH);
		String[] dir = DianningUtil.getDirById(uid);
		String formjpg = Constant.ROOTPATH + "/" + Constant.AVATAR_PATH + "/" + dir[0] + "/" + dir[1] + "/" + dir[2] + "/" + dir[3] + ".jpg";
		OutputStream bos = new FileOutputStream(formjpg);
		IOUtils.copy(uploadFile.getInputStream(), bos);
		bos.close();
		uploadFile = null;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		//ImgUtil.reduceImgNoLogo(formjpg, formjpg,100,100);	//jmagick版
		ImgUtil.reduceImg(formjpg, formjpg,100,100);
		return flag;
 }
 
 public String findAvatar(long uid){
	 String[] dir = DianningUtil.getDirById(uid);
	 String s = dir[0] + "/" + dir[1] + "/" + dir[2] + "/" + dir[3] + ".jpg";
	 File f = new File(Constant.ROOTPATH + "/" + Constant.AVATAR_PATH + "/" + s);
	 if(f.isFile()){
		 return Constant.DOMAIN + "/" + Constant.AVATAR_PATH + "/" + s;
	 }else{
		 return Constant.DOMAIN + "/" + Constant.DEFAULT_AVATAR_PATH;
	 }
 }
}
